﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ComponentModel;

namespace FXnaAppBase
{

    /// <summary>
    /// 提供dos运行的多方位函数与交互支持
    /// 首先就是消息事件的订阅
    /// </summary>
    public  class DosService
    {

        public DosService(BackgroundWorker worker)
        {
            this._worker = worker;

 
        }

        BackgroundWorker _worker;



        public void Run(RunData data)
        {

            data.BeforeRun();



            foreach (RunCommand command in data.Commands)
            {



                //这里需要考虑，异步执行，以及异步执行是否已经完成，避免先后循序的异步混乱

                command.BeforeRun();


                DosCommand dc = new DosCommand();

                dc.Process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(Process_ErrorDataReceived);
                dc.Process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(Process_OutputDataReceived);


                bool b= dc.RunExeCommand(command.ExeName,command.ExeArgs,command.WorkPath);

               


                dc.Process.ErrorDataReceived -= new System.Diagnostics.DataReceivedEventHandler(Process_ErrorDataReceived);
                dc.Process.OutputDataReceived -= new System.Diagnostics.DataReceivedEventHandler(Process_OutputDataReceived);



                if (!b)
                {

                    //运行失败的话，就退出
                    return;


                    
                }


                command.AfterRun();




                
            }




            data.AfterRun();

 
        }

        void Process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            
            this._worker.ReportProgress(1,e.Data);
            
        }

        void Process_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {

            //这里我们先做一个假设，0 表示错误 1表示正常数据，
            //这里是为了减少自定义消息对象，所引起长时间运行的问题。


            this._worker.ReportProgress(0, e.Data);
           
        }




    }
}
